﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using WebServer.dk.madis.flexibus;

namespace WebServer
{
    public partial class Default : System.Web.UI.Page
    {
        IFormatProvider culture = new System.Globalization.CultureInfo("da-DK", true);


        protected void Page_Load(object sender, EventArgs e)
        {
            

            if (!IsCallback && !IsPostBack)
            {
                fillRoutesList();

                dk.madis.flexibus.WebAPI service = new dk.madis.flexibus.WebAPI();
                String[] dropOffs = service.GetDropOffPoints();
                foreach (String item in dropOffs)
                {
                    DropOffPoints.Items.Add(new ListItem(item, item));
                }

                DropOffDateField.Value = DateTime.Now.AddDays(1).ToShortDateString();
                DropOffTimeField.Value = DateTime.Now.ToShortTimeString();

                TfromDate.Value = DateTime.Now.ToShortDateString();
                TtoDate.Value = DateTime.Now.ToShortDateString();
                TfromTime.Value = new DateTime(2012, 1, 1, DateTime.Now.Hour, 0, 0).ToShortTimeString();
                TtoTime.Value = new DateTime(2012, 1, 1, DateTime.Now.AddHours(1.0).Hour, 0, 0).ToShortTimeString();
            }

        }

        protected void send_button_Click(object sender, EventArgs e)
        {
            String citizenID = CitizenIdField.Value;
            String pickupLocation = PickupLocationField.Value;
            String dropOffLocation = DropOffPoints.SelectedValue;
            String dropOffDate = DropOffDateField.Value + " " + DropOffTimeField.Value;
            DateTime dropOffDateTime = new DateTime();

            if (citizenID.Equals("") || pickupLocation.Equals("") || dropOffLocation.Equals("") || !DateTime.TryParse(dropOffDate, culture, System.Globalization.DateTimeStyles.AssumeLocal, out dropOffDateTime))
            {
                return;
            }

            try
            {
                using (dk.madis.flexibus.WebAPI service = new dk.madis.flexibus.WebAPI())
                {

                    WebServer.dk.madis.flexibus.Transport request = new WebServer.dk.madis.flexibus.Transport()
                    {
                        CitizenID = citizenID,
                        PickupAdress = pickupLocation,
                        DropOffLocation = dropOffLocation,
                        DropOffTime = dropOffDateTime
                    };

                    if (service.RequestWithFixedDropOffTime(request) > 0)
                    {
                        infoMsg.InnerText = "Request succesfully sent.";
                        infoMsg.Attributes.Remove("class");
                    }
                    else
                    {
                        infoMsg.InnerText = "Request was not received properly, try to recheck values.";
                        infoMsg.Attributes.Add("class", "notfound");
                    }
                }
            }
            catch (Exception ex)
            {
                String ErrorMsg = ex.Message;
                infoMsg.InnerHtml = string.Format("Request was not received properly, please check error message: <br/>{0}", ErrorMsg);
                infoMsg.Attributes.Add("class", "notfound");
            }
        }



        protected void getTransports_button_Click(object sender, EventArgs e)
        {

            DateTime from = new DateTime();
            DateTime to = new DateTime();

            if (!DateTime.TryParse(String.Format("{0} {1}", TfromDate.Value, TfromTime.Value), culture, System.Globalization.DateTimeStyles.AssumeLocal, out from)
                || !DateTime.TryParse(String.Format("{0} {1}", TtoDate.Value, TtoTime.Value), culture, System.Globalization.DateTimeStyles.AssumeLocal, out to))
            {
                InfoMsg2.InnerHtml = string.Format("The dates were not formatted correctly, they should be on the form: dd-mm-yy HH:mm");
                InfoMsg2.Attributes.Add("class", "notfound");
                return;
            }


            using (dk.madis.flexibus.WebAPI service = new dk.madis.flexibus.WebAPI())
            {
                Transport[] transports = service.GetTransports_DropoffBetweenDateTimes(from, to);
                TransportList.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
                if (transports.Length > 0)
                {
                    TableRow row = new TableRow();
                    row.TableSection = TableRowSection.TableHeader;
                    TableCell cell = new TableCell();
                    cell.Text = "Citizen ID"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Pickup Adress"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Drop Off Location"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "DropOff Time"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Route ID"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = ""; row.Cells.Add(cell);
                    TransportList.Rows.Add(row);

                }

                foreach (Transport transport in transports)
                {
                    TableRow row = new TableRow();
                    row.TableSection = TableRowSection.TableBody;
                    TableCell cell = new TableCell();
                    cell.Text = transport.CitizenID; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = transport.PickupAdress; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = transport.DropOffLocation; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = transport.DropOffTime.ToShortTimeString(); row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = String.Format("{0}", transport.RouteID); row.Cells.Add(cell);
                    cell = new TableCell();

                    //TODO: lav knap til "annullering"
                    HtmlButton button = new HtmlButton()
                    {
                        InnerText = "Cancel",
                        ID = "trans_"+transport.ID,
                    };
                    button.ServerClick += button_CancelTransportClick;
                    cell.Text = "Route ID"; row.Cells.Add(cell);
                    TransportList.Rows.Add(row);
                }
            }
            fillRoutesList();
        }

        void button_CancelTransportClick(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            try
            {
                String strTransportID = btn.ID.Split('_')[1];
                Int32 transportID = 0;
                if (int.TryParse(strTransportID, out transportID))
                {
                    using (dk.madis.flexibus.WebAPI service = new dk.madis.flexibus.WebAPI())
                    {
                        if (service.CancelRequest(transportID))
                        {
                            fillRoutesList();
                        }
                    }
                }
            }
            catch (Exception eof)
            {

            }
            
        }

        protected void calculateTransport_button_Click(object sender, EventArgs e)
        {

            DateTime from = new DateTime();
            DateTime to = new DateTime();

            if (!DateTime.TryParse(String.Format("{0} {1}", TfromDate.Value, TfromTime.Value), culture, System.Globalization.DateTimeStyles.AssumeLocal, out from)
                || !DateTime.TryParse(String.Format("{0} {1}", TtoDate.Value, TtoTime.Value), culture, System.Globalization.DateTimeStyles.AssumeLocal, out to))
            {
                InfoMsg2.InnerHtml = string.Format("The dates were not formatted correctly, they should be on the form: dd-mm-yy HH:mm");
                InfoMsg2.Attributes.Add("class", "notfound");
                return;
            }

            try
            {
                WebServer.Models.RouteCalculator calc = new WebServer.Models.RouteCalculator();
                String dropOffName = "Banegården";
                calc.CalculateNewRoute(from, to, dropOffName);

                fillRoutesList();
            }
            catch (Exception exce)
            {
                String ErrorMsg = exce.Message;
                InfoMsg2.InnerHtml = string.Format("New route not calculated, please check error message: <br/>{0}", ErrorMsg);
                InfoMsg2.Attributes.Add("class", "notfound");
                return;
            }

        }

        protected void deleteEverything_button_Click(object sender, EventArgs e)
        {
            using (WebServer.Models.StorageConnectorDataContext context = new Models.StorageConnectorDataContext())
            {
                // context.Transports.DeleteAllOnSubmit(from t in context.Transports select t);
                context.Waypoints.DeleteAllOnSubmit(from w in context.Waypoints select w);
                context.Instructions.DeleteAllOnSubmit(from i in context.Instructions select i);
                context.SubmitChanges();
                context.Routes.DeleteAllOnSubmit(from r in context.Routes select r);
                context.SubmitChanges();
            }
        }

        private void fillRoutesList()
        {
            using (WebServer.Models.StorageConnectorDataContext context = new Models.StorageConnectorDataContext())
            {
                var routes = context.Routes.OrderBy(d => d.ArrivalTime);
                routesList.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
                if (routes.Count() > 0)
                {
                    TableRow row = new TableRow();
                    row.TableSection = TableRowSection.TableHeader;
                    TableCell cell = new TableCell();
                    cell.Text = "ID"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Arrival time"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Start"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "End"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Duration"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Distance"; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = "Maps link"; row.Cells.Add(cell);
                    routesList.Rows.Add(row);

                }

                foreach (WebServer.Models.Route route in routes)
                {
                    TableRow row = new TableRow();
                    row.TableSection = TableRowSection.TableBody;
                    TableCell cell = new TableCell();
                    cell.Text = String.Format("{0}",route.ID); row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = String.Format("{0}, {1}", route.ArrivalTime.ToShortDateString(), route.ArrivalTime.ToShortTimeString()); row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = route.StartAddress; row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = route.EndAddress; row.Cells.Add(cell);
                    cell = new TableCell();
                    TimeSpan span = new TimeSpan(0, route.Duration, 0);
                    cell.Text = span.ToString(); row.Cells.Add(cell);
                    cell = new TableCell();
                    cell.Text = String.Format("{0} km", route.Distance); row.Cells.Add(cell);

                    HyperLink a = new HyperLink();
                    a.NavigateUrl = route.GoogleMapsUrl;
                    a.Text = ">>";
                    a.Target = "_blank";
                    cell = new TableCell();
                    cell.Controls.Add(a); row.Cells.Add(cell);
                    routesList.Rows.Add(row);
                }
            }

        }
    }
}